package com.book.modules.interceptor;

import com.book.common.api.oauth.HystrixConstant;
import com.book.common.helper.I18nHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Description：国际化处理，Dubbo可以在这里通过隐式传参实现语言通信
 * 传参：RpcContext.getContext().setAttachment(I18nHelper.LANGUAGE, lang);
 * 使用：RpcContext.getContext().getAttachment(I18nHelper.LANGUAGE)
 * 线程级，所以对象是安全的
 *
 * @Author： leo.xiong
 * @CreateDate： 2020/07/10 14:46
 * @Email： leo.xiong@suyun360.com
 * @Since：
 */
@Component
public class LanguageInterceptor implements HandlerInterceptor {

    @Autowired
    private I18nHelper i18nHelper;

    /**
     * RPC隐式传参，所有的RPC链路都可以获取到
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        i18nHelper.setLocale(request.getHeader(HystrixConstant.LOCAL_KEY), null);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        i18nHelper.removeLocale();
    }
}
